#include <stdio.h>
#include <assert.h>

#include "user_threads.h"
#include "user_mutex.h"

uthread_mutex_t mutex;

#ifdef ENABLE_UPRINT
#define UPRINT(...)	\
	do { \
		printf("=> TEST | %s:%d -> ", __FILE__, __LINE__);	\
		printf(__VA_ARGS__);	\
		printf("\n");	\
	} while (0)
#else
#define UPRINT(...)
#endif

int test_proc(void* arg)
{
	int i;

	printf("I'm a new thread with tid=%d.\n", uthread_self());

	for (i = 0; i < 10; ++i) {
		//*
		UPRINT("thread %d locking mutex\n", uthread_self());
		assert(MUTEX_SUCCESS == uthread_mutex_lock(mutex));
		UPRINT("thread %d locked mutex -> yielding\n", uthread_self());
		uthread_yield();
		UPRINT("thread %d unlocking mutex\n", uthread_self());
		assert(MUTEX_SUCCESS == uthread_mutex_unlock(mutex));
		UPRINT("thread %d unlocked mutex->yielding\n", uthread_self());
		uthread_yield();
		//*/
	}

	if (uthread_self() != 2)
	{
		UPRINT("exiting thread with tid=%d\n", uthread_self());
		uthread_exit(uthread_self());
	}

	UPRINT("returning from thread with tid=%d\n", uthread_self());

	return uthread_self();
}

int main111(int argc, char** argv)
{
	thread_id tid;

	UPRINT("Entry tid=%d\n", uthread_self());

	assert(MUTEX_SUCCESS == uthread_mutex_init(&mutex));

	UPRINT("Created a new mutex");

	tid = uthread_create(test_proc, NULL);
	UPRINT("Created a new thread with tid=%d\n", tid);

	tid = uthread_create(test_proc, NULL);
	UPRINT("Created a new thread with tid=%d\n", tid);

	test_proc(NULL);

	return 0;
}
